/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.edu.zut.jdbcpool.datasource;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.LinkedList;

/**
 *
 * @author jyc
 */
public abstract class BaseDataSource extends AbstractDataSource {
    // ********** Initial Variable **********
    private String driverClassName;
    private String url;
    private String username;
    private String password;
    private int initialSize = 5;
    private int maxSize = 10;
    // ********** Connection Pool **********
    protected LinkedList<Connection> dbPool = null;

    public BaseDataSource() {
    }

    public BaseDataSource(String url, String username, String password) {
        this.url = url;
        this.username = username;
        this.password = password;
    }

    public BaseDataSource(String driverClassName, String url, String username, String password) {
        this.driverClassName = driverClassName;
        this.url = url;
        this.username = username;
        this.password = password;
    }
    
    @Override
    public Connection getConnection() throws SQLException {
        if(dbPool == null) {
            initPool();
        }
        return requireConnection();
    }

    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        setUsername(username);
        setPassword(password);
        return getConnection();
    }
    
    /**
     * 初始化数据库连接池
     */
    protected abstract void initPool();
    
    /**
     * 从当前数据库连接池中获取一条连接
     * @return 数据库连接，如果当前连接池中无活动连接，则返回null
     */
    protected abstract Connection requireConnection();

    public String getDriverClassName() {
        return driverClassName;
    }

    public void setDriverClassName(String driverClassName) {
        this.driverClassName = driverClassName;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public int getInitialSize() {
        return initialSize;
    }

    public void setInitialSize(int initialSize) {
        this.initialSize = initialSize;
    }

    public int getMaxSize() {
        return maxSize;
    }

    public void setMaxSize(int maxSize) {
        this.maxSize = maxSize;
    }
}
